package com.only4play.practice.invoice.core.domainservice.pipeline.filters.register;

import com.only4play.codegen.support.exception.BusinessException;
import com.only4play.practice.invoice.core.enums.InvoiceErrorCode;
import com.only4play.practice.common.exception.BizException;
import com.only4play.practice.invoice.api.model.OrderRegisterModel;
import com.only4play.practice.invoice.api.model.OrderRegisterResultModel;
import com.only4play.practice.invoice.api.model.resp.TaxRateConfigResponse;
import com.only4play.practice.invoice.core.domainservice.pipeline.context.OrderReceiptContext;
import com.only4play.practice.invoice.core.facade.IInvoicePipeLineFacadeService;
import com.only4play.practice.objectsku.api.model.resp.ObjectSkuResponse;
import com.only4play.practice.ordercommon.filters.AbstractOrderFilter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 解析订单项到凭据项
 */
@RequiredArgsConstructor
@Slf4j
public class PopulateReceiptItemFilter extends AbstractOrderFilter<OrderReceiptContext> {

  private final IInvoicePipeLineFacadeService facadeService;

  @Override
  protected void handle(OrderReceiptContext orderReceiptContext) {
    List<OrderRegisterModel.OrderRegisterItem> orderItems = orderReceiptContext.getModel().getOrderItems();
    List<OrderRegisterResultModel.ResultItem> resultItems = orderItems.stream()
        .map(item -> {
          Long skuId = item.getSkuId();
            ObjectSkuResponse objectSkuResponse = facadeService.getOrderFacadeService()
                    .findSkuInfoById(skuId);

          Optional<TaxRateConfigResponse> taxRateConfig = facadeService.getInvoiceFacadeService()
              .findRateConfigByTaxCategoryCode(objectSkuResponse.getTaxCategoryNo());

          if (!taxRateConfig.isPresent()) {
            throw new BusinessException(InvoiceErrorCode.TAX_RATE_NOT_CONFIG);
          }
            return orderItemConvert(item, taxRateConfig.get(), objectSkuResponse);
        }).collect(Collectors.toList());
    orderReceiptContext.getRegisterResultModel().setItems(resultItems);
  }

  private OrderRegisterResultModel.ResultItem orderItemConvert(OrderRegisterModel.OrderRegisterItem item,
      TaxRateConfigResponse vo,ObjectSkuResponse skuVo){

    OrderRegisterResultModel.ResultItem resultItem = new OrderRegisterResultModel.ResultItem();
    resultItem.setItemUnit(item.getItemUnit());
    resultItem.setCount(item.getCount());
    resultItem.setDisplayName(vo.getDisplayName());
    resultItem.setSkuId(skuVo.getId());
    resultItem.setSkuName(skuVo.getSkuName());
    resultItem.setTaxRate(vo.getTaxRate());
    resultItem.setTaxCategory(vo.getTaxCategory());
    resultItem.setTaxCategoryCode(vo.getTaxCategoryCode());
    resultItem.setAmount(item.getAmount());
    return resultItem;
  }
}
